package com.neusoft.filter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import com.neusoft.feign.AuthFeignClient;
import com.neusoft.po.CommonResult;

import reactor.core.publisher.Mono;

@Component
public class AuthFilter implements GlobalFilter{

	@Autowired
	private AuthFeignClient authFeignClient;
	
	@Override
	public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
		
		
		// 对登录请求进行放行
		if (exchange.getRequest().getPath().toString().contains("UserController")) {
			return chain.filter(exchange);
		}
		if (exchange.getRequest().getPath().toString().contains("AuthController")) {
			return chain.filter(exchange);
		}
		// 获取请求参数中的token
		String token = exchange.getRequest().getQueryParams().getFirst("token");
		CommonResult result = authFeignClient.checkToken(token);
		if (result.getCode().equals(Integer.valueOf(401))) {
			exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
			return exchange.getResponse().setComplete();
		}
		
		return chain.filter(exchange);
		


	}
}
